#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

char *SOCK_PATH;

int main(int argc, char **argv) {

	int s, t, len;
	    struct sockaddr_un remote;
	    char str[100];

	    if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
	        perror("socket");
	        exit(1);
	    }

	   // printf("Trying to connect...\n");
		SOCK_PATH = (char*)malloc(strlen(argv[0])+1);
		strcpy(SOCK_PATH, argv[0]);
	    remote.sun_family = AF_UNIX;
	    strcpy(remote.sun_path, SOCK_PATH);
	    len = strlen(remote.sun_path) + sizeof(remote.sun_family);
	    if (connect(s, (struct sockaddr *)&remote, len) == -1) {
	        perror("connect");
	        exit(1);
	    }

	//    printf("Connected.\n");


	    while (1) {
		printf("\ncomando> ");
		fgets(str, 100, stdin);
		if (send(s, str, strlen(str), 0) == -1) {
			perror("send");
			exit(1);
		}
		if (str[0] == 'e')
			break;
		while (strstr(str, "Fin") == NULL) {
			if ((t = recv(s, str, 100, 0)) > 0) {
				str[t] = '\0';
				printf("%s", str);
			} else {
				if (t < 0)
					perror("recv");
				else
					printf("Server closed connection\n");
				exit(1);
			}
		}
	}
	close(s);
	exit(0);
}
